package cn.edu.cqupt.cxcy.util;

import java.io.File;
import java.security.MessageDigest;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Tools {

	/**
	 * 生成md5
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		if(message == null) {
			message = "";
		}
		String md5str = "";
		try {
			//1 创建一个提供信息摘要算法的对象，初始化为md5算法对象
			MessageDigest md = MessageDigest.getInstance("MD5");
			//2 将消息变成byte数组
			byte[] input = message.getBytes();
			//3 计算后获得字节数组,这就是那128位了
			byte[] buff = md.digest(input);
			//4 把数组每一字节（一个字节占八位）换成16进制连成md5字符串
			md5str = bytesToHex(buff);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return md5str;
	}

	/**
	 * 二进制转十六进制
	 * @param bytes
	 * @return
	 */
	public static String bytesToHex(byte[] bytes) {
		StringBuffer md5str = new StringBuffer();
		//把数组每一字节换成16进制连成md5字符串
		int digital;
		for (int i = 0; i < bytes.length; i++) {
			digital = bytes[i];
			if(digital < 0) {
				digital += 256;
			}
			if(digital < 16){
				md5str.append("0");
			}
			md5str.append(Integer.toHexString(digital));
		}
		return md5str.toString().toUpperCase();
	}

	/**
	 * 把数字转化为空格分开的字符串;如 456:4 5 6;
	 * @param ness
	 * @return
	 */
	public static List<String> int2String(List<Integer> ness) {
		List<String> ne = new ArrayList<>();
		for(int i=0; i<ness.size(); i++) {
			String ii = Integer.toString(ness.get(i));
			String ww = "";
			for(int q=0; q<ii.length(); q++) {
				if(q == ii.length()-1) {
					ww += ii.charAt(q);
				} else {
					ww += ii.charAt(q) + " ";
				}
			}
			ne.add(ww);
		}
		return ne;
	}

	/**
	 * 产生随机的字符串
	 * @param length 字符串长度
	 * @return 一个字符串
	 */
	public static String getRandomString(int length) { //length表示生成字符串的长度  
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
		Random random = new Random();     
		StringBuffer sb = new StringBuffer();     
		for (int i = 0; i < length; i++) {     
			int number = random.nextInt(base.length());     
			sb.append(base.charAt(number));     
		}     
		return sb.toString();     
	}
	/**
	 * 获取中文时间
	 */
	public static String getDateCN(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		return format.format(System.currentTimeMillis());
	}
	/**
	 * 获取英文时间
	 */
	public static String getDateEN(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(System.currentTimeMillis());
	}

	/**
	 * 获取英文时间
	 */
	public static String getDateyyyyMMdd(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(System.currentTimeMillis());
	}
	/**
	 * 返回如 12:00:00
	 * @param time
	 * @return
	 */
	public static Time getTimeddHHmm(String date) {
		java.sql.Time sqltime = java.sql.Time.valueOf(date); 
		return sqltime;
	}
	/**
	 * 返回如2008-07-10 12:00
	 * @param date
	 * @return
	 */
	public static Date getDateyyyyMMdd(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd");
		Date dt = null;
		try {
			dt = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dt;
	}
	/**
	 * 上传文件或者图片 返回
	 */
	public static List<String[]> fileUpload(HttpServletRequest request,HttpServletResponse response){
		//获取磁盘文件条目空间
		//String[] names = new String[2];//字符串数组,用于保存文件的真实路径和文件名
		response.setContentType("text/html;charset=utf-8");
		List<String[]> list = new ArrayList<>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String savePath = request.getServletContext().getRealPath("/fileOrImg");
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		factory.setRepository(new File(savePath));
		factory.setSizeThreshold(1024*1024*1024);
		try {
			List<FileItem> items = upload.parseRequest(request);
			for(FileItem item:items){
				if(!item.isFormField() && item != null){
					String[] names = new String[3];//字符串数组,分别为文件类型,数据库中存储的文件名,文件保存到服务器的地址
					//String name = item.getName();
					String foot = item.getName().substring(item.getName().indexOf("."));
					String realFileName = getRandom(10)+foot;
					String dbName = item.getName().substring(item.getName().lastIndexOf("\\")+1);
					names[0] = item.getFieldName();//得到文件的名称,可以用这个参数来识别上传的文件类型
					names[1] = savePath+"/"+realFileName;
					names[2] = dbName;
					File file = new File(savePath,realFileName);
					if(!file.exists()){
						file.createNewFile();
					}
					item.write(file);
					list.add(names);
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}catch(Exception e1){
			e1.printStackTrace();
		}
		return list;
	}
	/**
	 * 得到指定位数的随机数
	 * @param index
	 * @return
	 */
	public static String getRandom(int index){
		StringBuilder builder = new StringBuilder();
		Random random = new Random();
		for(int i = 0;i<index;i++){
			builder.append(random.nextInt(10));
		}
		return builder.toString();
	}
	public static String getImgSrc(String data) {
		if( data == null) {
			return "";
		}
		return data.substring( data.indexOf("<img src=\"u")+10, data.indexOf("\"", data.indexOf("<img src=\"u")+10));
	}
	
	/**
	 * 过滤任意(script,html,style)标签符,返回长度不大于len的纯文
	 * @param inputString
	 * @param len
	 * @return
	 */
	public static String Html2Text(String inputString, int len) {
		if(inputString == null) {
			return "";
		}
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}
		return textStr.length() > len ? textStr.substring(0, len) : textStr;// 返回文本字符串
	}
	
	/**
	 * 对html进行转义
	 * @param content
	 * @return
	 */
	public static String html(String content) {
		 if(content==null) return "";        
		     String html = content;
		      
		 //    html = html.replace( "'", "&apos;");
		     html = html.replaceAll( "&", "&amp;");
		     html = html.replace( "\"", "&quot;");  //"
		     html = html.replace( "\t", "&nbsp;&nbsp;");// 替换跳格
		     html = html.replace( " ", "&nbsp;");// 替换空格
		     html = html.replace("<", "&lt;");
		  
		     html = html.replaceAll( ">", "&gt;");
		    
		     return html;
		 }
}
